package com.cloudserver.springboot.controller;

import com.cloudserver.springboot.Constants.*;
import com.cloudserver.springboot.bean.Character;
import com.cloudserver.springboot.bean.User;
import com.cloudserver.springboot.service.PermissionService;
import com.cloudserver.springboot.service.UserService;
import com.cloudserver.springboot.utils.CommonResult;
import com.cloudserver.springboot.utils.MapUntil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.Optional;

/**
 * @Description: UserController 类是 处理用户的登录、添加、删除、修改等操作
 * @author zqq
 * @create 2020-10-06 14:31
 */
@RestController
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    /**
     * @Description: doLogin  处理登录请求
     * @param: [account: 账户, password：密码]
     * @return: com.cloudserver.springboot.utils.CommonResult
     * @auther: zqq
     * @date: 20/10/6 15:20
     */
    @PostMapping(value = "/login")
    @CrossOrigin   // 解决跨域
    public CommonResult doLogin(@RequestParam("username") @NotNull String account,
                                @RequestParam("password") @NotNull String password,
                                HttpSession session){
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        Integer code = userService.loginservice(user);
        CommonResult commonResult = null;
        if (code == LoginInfo.ACCOUNT_NOT_EXIT_CODE){
            commonResult = new CommonResult(code, LoginInfo.ACCOUNT_NOT_EXIT_MSG);
        }else if (code == LoginInfo.PASSWORD_ERROR_CODE){
            commonResult = new CommonResult(code, LoginInfo.PASSWORD_ERROR_MSG);
        }else {
            Character allById = permissionService.getAllById(code);
            Optional<Character> byId = Optional.ofNullable(allById);
            if (byId.isPresent()){
                Character character = byId.get();
                if ( character.getCharacterName().equals(CharacterInfo.VISITOR)){ // visiter用户不具备权限
                    commonResult = new CommonResult(LoginInfo.NOT_PERMISSION_CODE, LoginInfo.NOT_PERMISSION_CODE_MSG);
                }else if (character.getCharacterStatus() == CharacterInfo.CHARACTER_STATUS_ACTIVE){ // 角色激活激活
                    commonResult = new CommonResult(LoginInfo.SUCCESSCODE, LoginInfo.SUCCESSMSG);
                }else {//角色未激活
                    commonResult = new CommonResult(LoginInfo.CHARACTER_NOT_ACTIVE, LoginInfo.CHARACTER_NOT_ACTIVE_MSG);
                }
            }else { //未分配角色
                commonResult = new CommonResult(LoginInfo.NOT_HIVE_CHARACTER, LoginInfo.NOT_HIVE_CHARACTER_MSG);
            }
            Object attribute = session.getAttribute(UserSession.USER_MAP);
            MapUntil userMap = (MapUntil)attribute;
            Optional<MapUntil> opt = Optional.ofNullable(userMap);
            /**
             * 如果 opt 的值不为空（opt.isPresent()），直接获取 attribute 的值，并添加一条数据，重新保存到session中
             * 否则初始化一个固定长度的map，将数据以（k,v）的形式存储，k为账户，v为数据库查询的主键id，最后保存到session中
             *
             */
            if (opt.isPresent()){
                MapUntil mapUntil = opt.get();
                mapUntil.put(account, code);
                session.setAttribute(UserSession.USER_MAP, mapUntil);
            }else {
                MapUntil mapUntil = new MapUntil();
                mapUntil.put(account, code);
                session.setAttribute(UserSession.USER_MAP, mapUntil);
            }
        }
        return commonResult;
    }

    @PostMapping(value = "/adduser")
    @CrossOrigin
    public CommonResult adduser(User user) {
        boolean addUser = userService.addUser(user);
        CommonResult commonResult = new CommonResult<>();
        if (addUser) {
            commonResult.setCode(ResulInfo.SUCCESS);
            commonResult.setMessage(UserInfo.ADD_USER_SUCCESS_MSG);
            return commonResult;
        } else {
            commonResult.setCode(ResulInfo.ERROR);
            commonResult.setMessage(UserInfo.ADD_USER_ERROR_MSG);
            return commonResult;
        }
    }
}
